package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Reference
    UserService userService;

    @Reference
    RoleService roleService;


    /**
     * 获取用户名
     *
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername(HttpSession session) {
        //session.getAttribute("SPRING_SECURITY_CONTEXT");
        //session.getAttributeNames();  //可以获取session中所有的参数名
        //SecurityContextHolder 帮助类， 可以直接获取 session中 securityContext对象
        // SecurityContext: 上下文对象, 包含了用户信息和权限信息
        SecurityContext context = SecurityContextHolder.getContext();
        //获取认证对象
        Authentication authentication = context.getAuthentication();
        //获取principal 对象
        Object principal = authentication.getPrincipal();
        //如果 没有登录，获取到的是匿名用户，如果的登录了获取到的User对象
        //instanceof : 实例类型判断运算符
        String username = null;
        if (principal instanceof User) {
            User u = (User) principal;
            username = u.getUsername();
        }
        log.debug("获取到的用户名为：" + username);
        return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
    }

    /**
     * 登录成功后访问的方法
     * 登录成功以后： pages/main.html
     */
    @RequestMapping("/loginSuccess")
    public ModelAndView loginSuccess() {
        log.debug("登录成功!!");
        //在ModelAndView 中指定视图名称
        //默认为请求转发
        // 设置为重定向
        return new ModelAndView("redirect:http://localhost:83/pages/main.html");
    }

    /**
     * 登录失败后访问的方法
     * 登录失败以后：跳转到登录页面, 重新登录, 提示登录失败
     */
    @RequestMapping("/loginFail")
    public ModelAndView loginFail() {
        log.debug("登录失败!!");
        return new ModelAndView("redirect:http://localhost:83/login.html");
    }

    @RequestMapping("/addUser")
    public Result addUser(@RequestBody SysUser sysUser, Integer[] checkitemIds) {

        log.debug("从前端获得到的map集合======" + sysUser);
        log.debug("从前端获得到的role集合======" + checkitemIds);

        int userId = userService.addUser(sysUser);

        log.debug("从前端获得到的role集合======" + sysUser.getId());
        for (Integer checkitemId : checkitemIds) {
            userService.addUserRole(userId, checkitemId);
        }


        log.debug("添加用户成功!!!!!");
        return new Result(true, "添加新用户成功");
    }


    @RequestMapping("/findUserByPage")
    public Result findUserByPage(@RequestBody QueryPageBean queryPageBean) {
        log.debug(queryPageBean.toString());
        Map<String, Object> userByPage = userService.findUserByPage(queryPageBean);
        return new Result(true, "查询用户列表成功", userByPage);
    }

    @RequestMapping("/findByUserId")
    public Result findById(Integer id) {
        log.debug(" ===============" + id);
        SysUser user = userService.findUserById(id);
        user.setPassword("");
        List<Integer> rolesId = new ArrayList<>();
        for (Role role : user.getRoles()) {
            Integer roleId = role.getId();
            rolesId.add(roleId);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("rolesId", rolesId);
        if (user.getBirthday() != null)
            map.put("birthday", sdf.format(user.getBirthday()));
        System.out.println(user.toString());
        return new Result(true, "查询用户成功", map);
    }

    @RequestMapping("/findAllRole")
    public Result findAll() {
        List<Role> roles = userService.findAllRoleY();
        return new Result(true, "查询角色列表成功", roles);
    }

    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody SysUser sysUser, Integer[] rolesId) {
        log.debug(sysUser.toString());
        String password;
        if (sysUser.getPassword().length() == 0) {
            SysUser byUsername = userService.findByUsername(sysUser.getUsername());
            password = byUsername.getPassword();
        } else {
            password = sysUser.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            password = passwordEncoder.encode(password);
        }
        System.out.println(password);
        sysUser.setPassword(password);
        userService.updateUser(sysUser, rolesId);
        return new Result(true, "修改用户成功");
    }


    @RequestMapping("/deleUserById")
    public Result deleUserById(Integer id) {
        log.debug(id.toString());
        userService.delUserById(id);
        return new Result(true, "删除用户成功");
    }


}